package com.allianz.webapps.controllers;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.FileWriter;
import java.io.IOException;
import java.nio.channels.FileChannel;
import java.text.DateFormat;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.HashMap;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.dom4j.Document;
import org.dom4j.DocumentHelper;
import org.dom4j.Element;
import org.dom4j.io.OutputFormat;
import org.dom4j.io.XMLWriter;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.allianz.frame.utils.ImageUploadUtil;
import com.allianz.frame.utils.PropertiesUtil;
import com.allianz.frame.utils.StringUtil;
import com.allianz.webapps.https.interfaces.type001.pojo.User;
import com.allianz.webapps.https.interfaces.util.ObjectUtil;
import com.allianz.webapps.orderspojo.AppBase;
import com.fasterxml.jackson.core.JsonParseException;
import com.fasterxml.jackson.databind.JsonMappingException;
import com.fasterxml.jackson.databind.ObjectMapper;

import net.sf.json.JSONObject;
import sun.misc.BASE64Decoder;

@SuppressWarnings("restriction")
@Controller
@RequestMapping(value="/drdocAction")
public class DrdocController {
	
	@Autowired
	private ObjectMapper objectMapper;
	@Autowired
	private ObjectUtil objectUtil;
	
	/**
	 * 双录上传 drdoc.getPending
	 * @param request
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value="/getPending")
	@ResponseBody
	public String getPending(HttpServletRequest request) throws Exception{
		User user=(User) request.getSession().getAttribute("username");
		String body=objectUtil.requestParam(user, "drdoc.getPending");
		return body;
	}
	
	/**
	 * 上传图片
	 * @param request
	 * @return
	 * @throws IOException 
	 * @throws JsonMappingException 
	 * @throws JsonParseException 
	 */
	@RequestMapping(value="uploadImg")
	@ResponseBody
	public Map<String,Object> uploadImg(@RequestParam(value="jsonParam") String jsonParam,HttpServletRequest request) throws JsonParseException, JsonMappingException, IOException{
		Map<String,Object> map = new HashMap<String,Object>();
		try {
			AppBase obj=objectMapper.readValue(jsonParam, AppBase.class);
			//获取保单号
			@SuppressWarnings("unused")
			String policyRef = obj.getPolicyRef();
			//获取投保单号
			String insured = obj.getPreprintedNo();
			//获取上传图片类型
			String idtype = obj.getItemType();
		
		if(StringUtil.isNull(insured)){
			map.put("status", "error");
			map.put("msg", "缺少必要参数!");
			return map;
		}
		if (StringUtil.isNull(idtype)) {
			map.put("status", "error");
			map.put("msg", "缺少必要参数!");
			return map;
		}
		
			String fileName = "";
			
//		a、  抄录签字声明照片
//			b、  手持保险计划照片
//			c、   签署投保单照片
//			d、  手持身份证和保险条款合影
		if ("A".equals(idtype)) {
			fileName = "CTSS";
		}else if ("B".equals(idtype)) {
			fileName = "HIP";
		}else if ("C".equals(idtype)) {
			fileName = "SIP";
		}else if ("D".equals(idtype)) {
			fileName = "HDII";
		}
		
		//获取上传的图片
		String image = request.getParameter("image");//这个就是前端传来的base64图片数据
		image = image.replaceAll("data:image/jpg;base64,","");
	//  覆盖之前以拍过的照片		如果照片存在则删除原来的照片
			File file=new File(PropertiesUtil.getResourcePath()+"private/photo_temp/"+insured+"/"+idtype+"/");
			if(file.exists()){
				for (File fi : file.listFiles()) {
					if(fi.getName().contains(fileName)){
						fi.delete();
					}
				}
			}else{
				//路径不存在,重新创建
					file.mkdirs();
			}
			String realPath = PropertiesUtil.getResourcePath()+"private/photo_temp/"+insured+"/"+idtype+"/"+fileName+".jpg";
			
			BASE64Decoder decoder = new BASE64Decoder();
				byte[] decodedBytes;
					decodedBytes = decoder.decodeBuffer(image);
				for(int i=0;i<decodedBytes.length;++i){
					if(decodedBytes[i]<0){//调整异常数据  
	                	decodedBytes[i]+=256;  
	                }
				}
				FileOutputStream out = new FileOutputStream(realPath);
				out.write(decodedBytes);
				out.close();
				map.put("status", "success");
				map.put("msg", "上传成功!");
		} catch (IOException e) {
			e.printStackTrace();
			map.put("status", "error");
			map.put("msg", "上传失败!");
		}
		return map;
	}
	/**
	 * 双录上传 drdoc.afterUpload
	 * @param request
	 * @return
	 * @throws Exception
	 */
	@RequestMapping(value="/afterUpload")
	@ResponseBody
	public String afterUpload(@RequestParam(value="jsonParam") String jsonParam,HttpServletRequest request) throws Exception{
		Map<String,Object> map = new  HashMap<String, Object>();
		AppBase obj=objectMapper.readValue(jsonParam, AppBase.class);
		//获取保单号
		//String policyRef = request.getParameter("policyRef");
		String policyRef = obj.getPolicyRef();
		//获取投保单号
		//String insured = request.getParameter("preprintedNo");
		String insured = obj.getPreprintedNo();
		//获取上传图片类型
		//String idtype = request.getParameter("itemType");
		String idtype = obj.getItemType();
		if (StringUtil.isNull(policyRef)) {
			map.put("Status", "F");
			map.put("ErrMsg", "缺少必要参数!-1");
			JSONObject str=JSONObject.fromObject(map);
			return str.toString();
		}
		if(StringUtil.isNull(insured)){
			map.put("Status", "F");
			map.put("ErrMsg", "缺少必要参数!-2");
			JSONObject str=JSONObject.fromObject(map);
			return str.toString();
		}
		if (StringUtil.isNull(idtype)) {
			map.put("Status", "F");
			map.put("ErrMsg", "缺少必要参数!-3");
			JSONObject str=JSONObject.fromObject(map);
			return str.toString();
		}
		//   照片上传
		String flagFileString_photo_Directory = PropertiesUtil.getResourcePath()+"private/photo_temp/"+insured+"/"+idtype+"/";
		File flagFileString_photoDirectoryFile = new File(flagFileString_photo_Directory);
		if(!flagFileString_photoDirectoryFile.exists() || flagFileString_photoDirectoryFile.isFile()){
			flagFileString_photoDirectoryFile.mkdirs();
		}
		//获取ip地址
		String ipaddress=ImageUploadUtil.getIP(request);
		//上传&生成xml配置文件
		boolean flag = shadowXMLandFolderCreate(policyRef, insured,idtype,ipaddress, new Date());
		String body ="";
		if (flag) {
			body=objectUtil.requestParam(obj, "drdoc.afterUpload");
		//	body="";
		}else{
			map.put("Status", "F");
			map.put("ErrMsg", "生成影像文件失败!");
			JSONObject str=JSONObject.fromObject(map);
			return str.toString();
		}
		return body;
	}

	//生成影像上传的xml文件和目录
	public static boolean shadowXMLandFolderCreate(String policyRef,String preprintedNo,String idtype,String ipHost,Date date) throws IOException{
		try{
		DateFormat df = new SimpleDateFormat("yyyyMMddhhmmss");
			String endPath = "DR"+policyRef+"i"+date.getTime();
			//判断图片上传是否成功  不成功return false
			String picFilePath = PropertiesUtil.getResourcePath()+"private/photo_temp/"+preprintedNo+"/"+idtype+"/";
			File picFile=new File(picFilePath);
			if(!picFile.exists() || picFile.isFile()){
				return false;
			}
			//创建xml文件 放在固定的路径下
			String folderPath = PropertiesUtil.getResourcePath()+"private/shadow_upload/"+endPath+"/";
			File folderPathFile = new File(folderPath);
			folderPathFile.mkdirs();
			
			String fileName="";
			File[] filesss=picFile.listFiles();
			for (File file : filesss) {
				if (file !=null) {
					fileName=file.getName();
				}
			}
			File sourceFile = new File(picFilePath+fileName);
			File endFile = new File(folderPath+fileName);

			if(sourceFile.getName().contains("CTSS") || sourceFile.getName().contains("HIP") ||
					sourceFile.getName().contains("SIP") || sourceFile.getName().contains("HDII")){
				if(fileName.endsWith(".jpg")){
					copyFileUsingFileChannels(sourceFile,endFile);
				}
			}else{
				return false;
			}
			String SfileType="";
			if ("A".equals(idtype)) {
				SfileType="1175";
			}else{
				SfileType="1170";
			}
			FileWriter fw = new FileWriter(folderPath+"1.xml");
			Document document = DocumentHelper.createDocument();
			// 创建ImageBatch结点
			Element imageBatch = document.addElement("ImageBatch");
			// 生成ImageBatch的子接点policys
			Element policys = imageBatch.addElement("policys");
			// 生成policys的子接点policy

				Element policy = policys.addElement("policy");
				Element policyNo = policy.addElement("policyNo");
					policyNo.addText(policyRef);//保单号
				Element uploadUser = policy.addElement("uploadUser");
					uploadUser.addText("app");
				Element fileType = policy.addElement("fileType");
					fileType.addText(SfileType);
				Element taskType = policy.addElement("taskType");
					taskType.addText("03");
				Element scanTime = policy.addElement("scanTime");
					scanTime.addText(df.format(date));
				Element taskId = policy.addElement("taskId");
					taskId.addText(preprintedNo);
				Element source = policy.addElement("source");
					source.addText("2");
				Element fileNum = policy.addElement("fileNum");
					fileNum.addText("1");
				Element ip = policy.addElement("ip");
					ip.addText(ipHost);
					//
				Element files = policy.addElement("files");
				Element filename =files.addElement("filename");
				filename.addText(fileName);
						
			// 设置文件编码
			OutputFormat xmlFormat = new OutputFormat();
			xmlFormat.setEncoding("UTF-8");
			// 设置换行
			xmlFormat.setNewlines(true);
			// 生成缩进
			xmlFormat.setIndent(true);
			// 使用1个制表符进行缩进, 可以兼容文本编辑器
			xmlFormat.setIndent("\t");
			// 创建写文件方法
			XMLWriter xmlWriter = new XMLWriter(fw, xmlFormat);
			// 写入文件
			xmlWriter.write(document);
			// 关闭
			xmlWriter.close();
			return true;
	} catch (Exception e) {
		e.printStackTrace();
		return false;
	}
}
	//文件复制，source文件，dest目标文件
	@SuppressWarnings("resource")
	private static void copyFileUsingFileChannels(File source, File dest) throws IOException{
		FileChannel inputChannel = null;
		FileChannel outputChannel = null;
		try{
			inputChannel = new FileInputStream(source).getChannel();
			outputChannel = new FileOutputStream(dest).getChannel();
			outputChannel.transferFrom(inputChannel, 0, inputChannel.size());
		}finally{
			inputChannel.close();
			outputChannel.close();
		}
	}
}
